import React, { useState } from 'react';
import { Input, Modal, Form, message, Upload, Button, Select, Icon } from 'antd';
import PropTypes from 'prop-types';

import { addDict } from '@api/dict';
import validatorCreator from '@util/validator-creator';
import './index.less';

const prefixCls = 'dict-config-model';
const FormItem = Form.Item;
const { Option } = Select;
const LIMIT_SIZE = 1024 * 1024 * 20;
const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

function DictConfigModel(props) {
  const {
    modalVisible,
    changeModalVisible,
    getList,
    form: { getFieldDecorator }
  } = props;

  const [fileList, setFileList] = useState([]);
  const [fileLimitMsg, setFileLimitMsg] = useState('');
  const [count, setCount] = useState(0);

  const beforeUpload = file => {
    const { size = 0, type } = file;
    if (size === 0) {
      message.error('请确保您上传的文件内容不为空');
      return false;
    }
    if (size > LIMIT_SIZE) {
      setFileLimitMsg('该文件大小超过了限制（20M）');
      return false;
    }

    if (type !== 'text/plain') {
      setFileLimitMsg('请上传utf-8 txt文件');
      return false;
    }
    setFileList([file]);
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = () => {
      const count = reader.result.split('\n').filter(line => line.trim()).length || 0;
      setCount(count);
    };
    setFileLimitMsg('');
    return false;
  };

  const onRemove = () => {
    setFileList([]);
    setCount(0);
  };

  const onSubmit = () => {
    const {
      form: { validateFieldsAndScroll }
    } = props;

    validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      if (fileLimitMsg) {
        return message.warning(fileLimitMsg);
      }

      if (!fileList.length) {
        return message.error('请选择自定义字典文件');
      }

      if (count === 0) {
        return message.error('请确保您上传文件内有至少1条数据');
      }
      const body = {
        name: values.name,
        type: values.type,
        count
      };

      const payload = new FormData();
      for (let key in body) {
        payload.append(key, JSON.stringify(body[key]));
      }

      payload.append('file', fileList[0]);

      addDict(payload)
        .then(() => {
          message.success('添加自定义字典成功！');
          changeModalVisible(false);
          setFileList([]);
          getList();
        })
        .catch(err => {
          message.error(err.message || '添加自定义字典失败！');
        });
    });
  };

  const onCancel = () => {
    changeModalVisible(false);
    setFileLimitMsg('');
    setFileList([]);
  };

  return (
    <div className={prefixCls}>
      <Modal
        maskClosable={false}
        title={<span style={{ fontWeight: 600 }}>添加字典</span>}
        className={`${prefixCls}-modal`}
        visible={modalVisible}
        width={520}
        portManage
        onCancel={onCancel}
        onOk={onSubmit}
        destroyOnClose
      >
        <Form labelAlign="left" colon={false}>
          <FormItem {...formItemLayout} key="name" label="字典名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  validator: validatorCreator('名称', {
                    reg: /^[\u4e00-\u9fa5a-zA-Z0-9-、—\\_：~(s)]+$/,
                    required: true,
                    message: '您输入的格式有误，仅支持中文、英文、数字、特殊字符 - 、— _ ：~'
                  })
                },
                {
                  max: 32,
                  message: '您输入的内容超过32个字符限制'
                }
              ]
            })(<Input placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符" />)}
          </FormItem>
          <FormItem {...formItemLayout} key="type" label="字典类型">
            {getFieldDecorator('type', {
              rules: [{ required: true, message: '请选择字典类型!' }]
            })(
              <Select>
                <Option value="username">用户名字典</Option>
                <Option value="password">密码字典</Option>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="字典上传">
            <div className={`${prefixCls}-modal-upload`}>
              <Upload
                className="uploader"
                accept=".txt"
                fileList={fileList}
                beforeUpload={file => beforeUpload(file)}
                onRemove={onRemove}
              >
                <Button>
                  <Icon type="upload" />
                  上传utf-8 txt文件
                </Button>
              </Upload>
              <a
                className="download-example"
                download="weakpassword-template.txt"
                href="/weakpassword-template.txt"
              >
                下载模板
              </a>
            </div>
          </FormItem>
          {fileLimitMsg && <p className={`${prefixCls}-error`}>{fileLimitMsg}</p>}
          <div className="built-in-desc">上传文件在20M以内</div>
        </Form>
      </Modal>
    </div>
  );
}

DictConfigModel.propTypes = {
  modalVisible: PropTypes.bool,
  changeModalVisible: PropTypes.func,
  form: PropTypes.object.isRequired,
  getList: PropTypes.func
};

export default Form.create()(DictConfigModel);
